#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ==================================================
# @File    : cachedriver
# @IDE     : PyCharm
# @Author  : liuxiangui
# @Date    : 2023/10/28 21:33
# @Describe: 缓存文件处理
# ==================================================

import os
import json
from typing import Any, Text, Union
from shutil import rmtree
from library.tools.file_tool.setting import root_path


class CacheLocalFile:
    """ 设置、读取缓存 """

    def __init__(self, filename: Union[Text, None]) -> None:
        # self.cacheRootPath = os.path.join(root_path(), ".cache")
        self.cacheRootPath = ".cache"
        if not os.path.exists(self.cacheRootPath):
            os.mkdir(self.cacheRootPath)
        self.path = os.path.join(self.cacheRootPath, filename)
        if not os.path.exists(self.path):
            with open(self.path, 'w', encoding='utf-8') as file:
                file.write('{}')

    def add_cache(self, key: str, value: Any):
        with open(self.path, 'r', encoding='utf-8') as file:
            history_data = eval(file.read())
        with open(self.path, 'w', encoding='utf-8') as file:
            history_data.update({key: value})
            new_data = json.dumps(history_data, indent=4)
            file.write(new_data)

    def get_cache(self, key, default=None) -> Any:
        """
        获取缓存数据
        @param key: 获取的key
        @param default: 无法获取，设置默认值
        :return:
        """
        try:
            with open(self.path, 'r', encoding='utf-8') as file:
                return eval(file.read()).get(key)
        except FileNotFoundError:
            return default

    def clean_cache(self) -> None:
        """删除所有缓存文件"""
        if not os.path.exists(self.path):
            raise FileNotFoundError(f"您要删除的缓存文件不存在 {self.path}")
        os.remove(self.path)

    @classmethod
    def clean_all_cache(cls) -> None:
        """
        清除所有缓存文件
        :return:
        """
        rmtree(".cache")


class SaveTempData:
    def set_data(self, key, value):
        if key in list(self.__dict__.keys()):
            self.__dict__[key] = value
        else:
            self.__setattr__(key, value)

    def get_data(self, key: str, result=None):
        try:
            res = self.__getattribute__(key)
        except AttributeError:
            res = result
        return res

    def del_attribute(self, attr: str):
        if not callable(getattr(self, attr)):
            delattr(self, attr)

cacheFileDriver = CacheLocalFile("cache_data.json")
cacheClassDriver = SaveTempData()

def save_cache_to_file() -> None:
    for key, value in cacheClassDriver.__dict__.items():
        cacheFileDriver.add_cache(key, value)

